# -*- coding:utf-8 -*-
import cv2
import numpy as np

cap = cv2.VideoCapture(1)
width, height = 640, 480
cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)

# 创建HSV阈值数组
hsv_low = np.array([0, 0, 0])
hsv_high = np.array([179, 255, 255])  # 初始化为最大范围


# 创建轨迹条回调函数
def update_value(value, index, array, is_low=True):
    if is_low:
        array[index] = value
    else:
        array[index] = value


# 创建窗口
cv2.namedWindow('Adjust HSV')

# 创建轨迹条
cv2.createTrackbar('H low', 'Adjust HSV', 0, 179, lambda v: update_value(v, 0, hsv_low))
cv2.createTrackbar('H high', 'Adjust HSV', 179, 179, lambda v: update_value(v, 0, hsv_high, False))
cv2.createTrackbar('S low', 'Adjust HSV', 0, 255, lambda v: update_value(v, 1, hsv_low))
cv2.createTrackbar('S high', 'Adjust HSV', 255, 255, lambda v: update_value(v, 1, hsv_high, False))
cv2.createTrackbar('V low', 'Adjust HSV', 0, 255, lambda v: update_value(v, 2, hsv_low))
cv2.createTrackbar('V high', 'Adjust HSV', 255, 255, lambda v: update_value(v, 2, hsv_high, False))


# 显示文本辅助函数
def draw_info(img, hsv_low, hsv_high):
    cv2.putText(img, f"Low: {hsv_low}", (10, 20),
                cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 1)
    cv2.putText(img, f"High: {hsv_high}", (10, 50),
                cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 1)
    return img


while True:
    ret, frame = cap.read()
    if not ret:
        print("Failed to read frame")
        break

    # 转换为HSV并进行阈值处理
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    mask = cv2.inRange(hsv, hsv_low, hsv_high)

    # 创建带有信息的副本
    info_frame = frame.copy()
    info_frame = draw_info(info_frame, hsv_low, hsv_high)

    # 应用掩膜显示结果
    result = cv2.bitwise_and(frame, frame, mask=mask)

    # 显示图像
    cv2.imshow("Original", info_frame)
    cv2.imshow('Binary Mask', mask)
    cv2.imshow('Threshold Result', result)

    # 退出条件
    key = cv2.waitKey(1)
    if key == ord('q'):
        break
    elif key == ord('s'):  # 按 's' 键保存当前阈值
        print(f"Saved HSV thresholds - Low: {hsv_low}, High: {hsv_high}")

cap.release()
cv2.destroyAllWindows()